#!/usr/bin/env python
#coding:utf-8
from min_p import *
reload(sys)
sys.setdefaultencoding("utf-8")

from selenium import webdriver  
from selenium.webdriver.common.action_chains import ActionChains
from taobao_login import TAOBAO_LOGIN
from taobao_db import TB_DB




#淘宝获取订单数据
class TAOBAO_TRADE(TAOBAO_LOGIN):
    #打开订单页面
    def get_trades_list(self):
        try:
            self.driver.find_element_by_link_text(u"卖家中心").click()
            #trade_url = self.driver.find_element_by_link_text(u'已卖出的宝贝').get_attribute("href")
            #self.driver.get(trade_url)
            self.driver.get("https://trade.taobao.com/trade/itemlist/list_sold_items.htm?mytmenu=ymbb")
        except Exception, e:
            print e
            return log_wrong()

    #获取当前页的订单[订单编号1+订单时间,订单编号2+订单时间]
    def get_trades(self):
        try:
            order_fast_list=[]
            trades = self.driver.find_elements_by_class_name("item-mod__checkbox-label___cRGUj")
            #taobao_id = self.driver.find_elements_by_class_name("buyer-mod__name___S9vit")
            for i in range(len(trades)):
                order_id,order_time = trades[i].text.split("创建时间: ")
                order_id = order_id.replace("订单号: ","")
                order_fast_list.append("%s+%s"%(order_id,order_time))#,"buyer_name":taobao_id[i].text})
            #print order_fast_list
            return order_fast_list
        except Exception, e:
            print e
            return log_wrong()

    #获取订单详情
    def get_trade_info(self,order_id):
        try:
            self.driver.get("https://trade.taobao.com/trade/detail/trade_order_detail.htm?biz_order_id=%s"%order_id)
            order_data = self.driver.page_source
            time.sleep(1)
            json_data = re_one('(?<=JSON.parse\(\').+(?=\'\);)',order_data).replace('\\\"','"')
            #print json_data
            return json_data
        except Exception, e:
            print e
            return log_wrong()


    #获取订单列表[{订单编号1:{订单1信息}},{订单编号2:{订单2信息}}]
    def get_order_dic(self):
        try:
            order_dic = {}
            order_list = []
            states = self.driver.find_elements_by_class_name("text-mod__link___2PH1j")
            trades = self.driver.find_elements_by_class_name("item-mod__checkbox-label___cRGUj")
            taobao_id = self.driver.find_elements_by_class_name("buyer-mod__name___S9vit")
            for i in range(len(trades)):
                #print trades[i].text
                order_id,order_time = trades[i].text.split("创建时间: ")
                order_id = order_id.replace("订单号: ","")
                order_list.append(order_id)
                order_dic[order_id]={"buyer_name":taobao_id[i].text,"order_creat_time":order_time,"outer_iid":"","refund":"","order_state":""}
            for i in states:
                state_text = i.text
                state_id = i.get_attribute("data-reactid").split("$")[1].split(".")[0]
                if state_text in [u"等待买家付款",u"交易关闭",u"买家已付款",u"交易成功",u"卖家已发货"]:
                    order_dic[state_id]["order_state"]=state_text
            msg = self.driver.find_elements_by_class_name("item-mod__trade-order___2LnGB")
            for i in msg:
                order_id = i.text.split("\n")[0].split(u"创建时间")[0].split(u": ")[1]
                #print order_id,order_dic
                for ss in i.text.split("\n"):
                    if "商家编码" in ss:
                        order_dic[order_id]["outer_iid"]=ss.split("：")[-1]
                    elif "退款成功" in ss:
                        order_dic[order_id]["refund"]=u"退款成功"
                    elif "请卖家处理" in ss:
                        order_dic[order_id]["refund"]=u"请卖家处理"
                    elif "售后成功" in ss:
                        order_dic[order_id]["refund"]=u"售后成功"
                    else:pass
            order_list_all = []
            for i in order_list:
                order_list_all.append({i:order_dic[i]})
            return order_list_all
        except Exception, e:
            print e
            return log_wrong()
    #翻页
    def next_page(self):
        try:
            buttons = self.driver.find_elements_by_tag_name("button")#.get_attribute('disabled')
            for button in buttons:
                if "下一页" in button.text:
                    if button.get_attribute('disabled')==None:
                        button.click()
                        time.sleep(3)
                        return True
                    else:
                        return False
        except Exception, e:
            print e
            return log_wrong()

    #更新订单明细-最后一个字段
    def load_order_info(self,order_list):
        p_msg('update_detail %s orders'%len(order_list))
        new_tb = TB_DB()
        for i in order_list:
            order_id = i.keys()[0]
            #print order_id
            json_data = self.get_trade_info(order_id)
            new_tb.update(order_id,"order_json",json_data)
        p_msg('update_end')


    #导入数据到数据库
    def add_data(self,order_list):
        p_msg('update %s new orders'%len(order_list))
        new_tb = TB_DB()
        for i in order_list:
            #print i
            order_id = i.keys()[0]
            refund = i[order_id]["refund"]
            order_state = i[order_id]["order_state"]
            order_creat_time = i[order_id]["order_creat_time"]
            buyer_name = i[order_id]["buyer_name"]
            outer_iid = i[order_id]["outer_iid"]
            new_tb.add(order_id,order_creat_time,buyer_name,order_state,outer_iid,refund)
        p_msg('update_end')

    #检查订单是否需要更新
    def check_order(self,order_list_all):
        new_tb = TB_DB()
        last_order = new_tb.get_last()
        last_time = time_num(last_order[2])
        last_order_id = last_order[1]

        update_new_list = []
        update_list = []

        for i in order_list_all:
            order_id = i.keys()[0]
            order_time = i[order_id]["order_creat_time"]
            refund = i[order_id]["refund"]
            order_state = i[order_id]["order_state"]
            
            if time_num(order_time)>=last_time and order_id!=last_order_id:
                update_new_list.append(i)
            else:
                order_data = new_tb.search_one(order_id)
                if refund != order_data[6] or order_state != order_data[4]:
                    update_list.append(i)

        return update_new_list,update_list





if __name__ == '__main__':
    new = TAOBAO_TRADE()
    new.login()
    new.get_trades_list()#打开订单列表
    order_list = new.get_order_dic()#获取第一页订单列表
    while True:
        if new.next_page():#下一页
            order_list = order_list + new.get_order_dic()
        else:
            break
    updata_new_list,update_list = new.check_order(order_list)#检查订单是否需要更新
    updata_new_list.reverse()
    new.add_data(updata_new_list)
    new.load_order_info(updata_new_list+update_list)
    